import React, { useCallback, useEffect, useState } from 'react';
import { Button, Form, Input, Space, Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import http from '../../api/http';
import type { PopconfirmProps } from 'antd';
import type { FormProps } from 'antd';
import { message, Popconfirm } from 'antd';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

interface DataType {
    key: React.Key;
    id: number;
    title: string;
    content: string;
    createdAt: string;
}

const App: React.FC = () => {
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const [title, setTitle] = useState('');
    const [tag, setTag] = useState('');
    const [forms] = Form.useForm();

    const fetchData = async () => {
        const params: {
            page: number,
            pageSize: number,
            keyword?: string,
            tag?: string
        } = {
            page, pageSize
        }
        if (title) params.keyword = title;
    if (tag) params.tag = tag;
        const res = await http.get('/article/list', {
            params
        })
        console.log(res, '表格数据')
        const { rows, count } = res.data;
        setData(rows)
        setTotal(count)
    }

    useEffect(() => {
        fetchData()
    }, [page, pageSize, title, tag])

    const columns: TableColumnsType<DataType> = [
        {
            title: 'ID',
            dataIndex: 'id',
            sorter: {
                compare: (a, b) => a.id - b.id,
                multiple: 3,
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
        },
        {
            title: '内容',
            dataIndex: 'content',
        },
        {
            title: '时间',
            dataIndex: 'createdAt',
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Popconfirm
                        title="Delete the task"
                        description="Are you sure to delete this task?"
                        onConfirm={() => confirm(record.id)}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <Button danger>删除</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    const onChange: TableProps<DataType>['onChange'] = (pagination, filters, sorter, extra) => {
        console.log('params', pagination, filters, sorter, extra);
    };

    // 分页
    const change = (page: number, pageSize: number) => {
        setPage(page)
        setPageSize(pageSize)
    }

    // 删除
    const confirm: PopconfirmProps['onConfirm'] = useCallback((id) => {
        const newData = data.filter((item) => item.id !== id)
        setData(newData)
    }, [data])

    const cancel: PopconfirmProps['onCancel'] = (e) => {
        console.log(e);
        message.error('Click on No');
    };

    // 搜索
    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        setTitle(values.title);
        setTag(values.tag);
    };
    // 重置
    const handleReact = () => {
        setTitle('');
        setTag('');
        forms.resetFields()
    }

    return (
        <div>
            {/* 搜索表单 */}
            <Form
                name="basic"
                layout='inline'
                form={forms}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 1600 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="标题"
                    name="title"
                >
                    <Input />
                </Form.Item>

                <Form.Item<FieldType>
                    label="标签"
                    name="tag"
                >
                    <Input />
                </Form.Item>

                <Form.Item label={null}>
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                </Form.Item>

                <Form.Item label={null}>
                    <Button type="primary" onClick={() => handleReact()}>
                        重置
                    </Button>
                </Form.Item>
            </Form>
            <Table<DataType>
                columns={columns}
                dataSource={data}
                onChange={onChange}
                showSorterTooltip={{ target: 'sorter-icon' }}
                pagination={{
                    total: total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共有 ${total} 条`,
                    onChange: change
                }}
            />
        </div>
    )
}

export default App;